import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import 'package:photo_frame/router/router_context.dart';
import 'package:photo_frame/utils/localization_util.dart';
import 'package:photo_frame/widgets/app_bar_widget.dart';

class ScanPage extends StatefulWidget {
  const ScanPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _ScanPageState();
}

class _ScanPageState extends State<ScanPage> with WidgetsBindingObserver {
  final MobileScannerController controller = MobileScannerController(
    autoStart: false,
    useNewCameraSelector: true,
  );

  Barcode? _barcode;
  StreamSubscription<Object?>? _subscription;
  bool isBack = false;

  void _handleBarcode(BarcodeCapture barcodes) {
    if (mounted && !isBack) {
      isBack = true;
      print("scan res : ${barcodes.barcodes[0].displayValue}");
      ARouter.instance
          .pagePop(arguments: {"result": barcodes.barcodes[0].displayValue});
      // setState(() {
      //   _barcode = barcodes.barcodes.firstOrNull;
      // });
    }
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);

    _subscription = controller.barcodes.listen(_handleBarcode);

    unawaited(controller.start());
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (!controller.value.isInitialized) {
      return;
    }

    switch (state) {
      case AppLifecycleState.detached:
      case AppLifecycleState.hidden:
      case AppLifecycleState.paused:
        return;
      case AppLifecycleState.resumed:
        _subscription = controller.barcodes.listen(_handleBarcode);

        unawaited(controller.start());
      case AppLifecycleState.inactive:
        unawaited(_subscription?.cancel());
        _subscription = null;
        unawaited(controller.stop());
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: commonAppBar(
          AppLocalizationsWrapper.instance.unwrap(context).scanQRcode,
          actions: [
            CupertinoButton(
              padding: EdgeInsets.zero,
              onPressed: () async {
                final ImagePicker picker = ImagePicker();
                final XFile? image = await picker.pickImage(
                  source: ImageSource.gallery,
                );
                if (image == null) {
                  return;
                }
                final BarcodeCapture? barcodes = await controller.analyzeImage(
                  image.path,
                );

                if (!context.mounted) {
                  return;
                }
                if (barcodes?.barcodes[0].displayValue?.isNotEmpty == true) {}
                _handleBarcode(barcodes!);
              },
              child: Padding(
                padding: const EdgeInsets.all(4).copyWith(right: 12),
                child: Image.asset(
                  'images/icon_photo.png',
                  width: 25.5,
                  height: 22,
                ),
              ),
            )
          ]),
      backgroundColor: Colors.black,
      body: Stack(
        children: [
          MobileScanner(
            controller: controller,
            errorBuilder: (context, error, child) {
              if (error.errorCode == MobileScannerErrorCode.permissionDenied) {
                Fluttertoast.showToast(
                    msg: AppLocalizationsWrapper.instance
                        .unwrapNoCtx()
                        .pleaseTurnOnCameraPermissions);
              }
              print("MobileScanner : ${error.toString()}");
              return Text("error : ${error.errorDetails?.message ?? ""}");
            },
            fit: BoxFit.cover,
          ),
          Center(
            child: Image.asset(
              "images/icon_scan_frame.png",
              width: 175,
              height: 175,
            ),
          )
        ],
      ),
    );
  }

  @override
  Future<void> dispose() async {
    WidgetsBinding.instance.removeObserver(this);
    unawaited(_subscription?.cancel());
    _subscription = null;
    super.dispose();
    await controller.dispose();
  }
}
